use swc_common::Span;
use swc_ecma_ast::*;
use swc_ecma_visit::{Visit, VisitWith};

#[derive(Debug)]
pub struct DefineConfigAst {
    arg_object_span: Option<Span>,
    arg_object_value: Option<ObjectLit>,
}

impl DefineConfigAst {
    pub fn build(ast: &Module) -> Self {
        let mut visitor = Self {
            arg_object_span: None,
            arg_object_value: None,
        };
        ast.visit_with(&mut visitor);
        visitor
    }
    pub fn arg_object_span(&self) -> Option<Span> {
        self.arg_object_span
    }
    pub fn arg_object_value(&self) -> Option<ObjectLit> {
        self.arg_object_value.clone()
    }
}

impl Visit for DefineConfigAst {
    fn visit_call_expr(&mut self, node: &CallExpr) {
        if let Callee::Expr(expr) = &node.callee {
            if let Expr::Ident(Ident { ref sym, .. }) = **expr {
                if format!("{}", sym) == "defineConfig" {
                    if let Expr::Object(object_lit) = (*node.args[0].expr).clone() {
                        self.arg_object_value = Some(object_lit.clone());
                        self.arg_object_span = Some(object_lit.span);
                    }
                }
            }
        }
    }
}
